import {Directive, ElementRef, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';

@Directive({
  selector: '[gnFormFile]',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => FormFileDirective),
    multi: true
  }]
})
export class FormFileDirective implements ControlValueAccessor {

  private onChange = (_: any) => {
  }
  private onTouched = () => {
  }

  constructor(elementRef: ElementRef) {
    elementRef.nativeElement.onchange = (event) => {
      const reader = new FileReader();
      if (event.target.files && event.target.files.length > 0) {
        const file = event.target.files[0];
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.onChange({
            filename: file.name,
            fileType: file.type,
            value: (reader.result as string).split(',')[1]
          });
        };
      }
    };
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
  }

  writeValue(obj: any): void {
  }

}
